/**
 * Copyright &copy; 2012-2015 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.soccer.cms.modules.cms.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.soccer.cms.common.config.Global;
import com.soccer.cms.common.persistence.Page;
import com.soccer.cms.common.web.BaseController;
import com.soccer.cms.common.utils.ActionHelp;
import com.soccer.cms.common.utils.Encodes;
import com.soccer.cms.common.utils.StringUtils;
import com.soccer.cms.common.utils.image.ImageCropUtils;
import com.soccer.cms.common.utils.image.ImageUtils;
import com.soccer.cms.modules.cms.entity.Category;
import com.soccer.cms.modules.cms.entity.CropImage;
import com.soccer.cms.modules.cms.entity.Imageinfo;
import com.soccer.cms.modules.cms.service.ImageinfoService;

/**
 * 图片信息Controller
 * @author zouqh
 * @version 2015-05-29
 */
@SuppressWarnings("unused")
@Controller
@RequestMapping(value = "${adminPath}/cms/imageinfo")
public class ImageinfoController extends BaseController {

	@Autowired
	private ImageinfoService imageinfoService;
	
	@ModelAttribute
	public Imageinfo get(@RequestParam(required=false) String id) {
		Imageinfo entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = imageinfoService.get(id);
		}
		if (entity == null){
			entity = new Imageinfo();
		}
		return entity;
	}
	
	@RequiresPermissions("cms:imageinfo:view")
	@RequestMapping(value = {"index"})
	public String indexPage(Imageinfo imageinfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		return "modules/cms/imageinfoIndex";
	}
	
	@RequiresPermissions("cms:imageinfo:view")
	@RequestMapping(value = {"list", ""})
	public String list(Imageinfo imageinfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Imageinfo> page = imageinfoService.findPage(new Page<Imageinfo>(request, response), imageinfo); 
		model.addAttribute("page", page);
		return "modules/cms/imageinfoList";
	}

	@RequiresPermissions("cms:imageinfo:view")
	@RequestMapping(value = "form")
	public String form(Imageinfo imageinfo, Model model) {
		model.addAttribute("imageinfo", imageinfo);
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("opt",request.getParameter("opt"));
		return "modules/cms/imageinfoForm";
	}

	@RequiresPermissions("cms:imageinfo:edit")
	@RequestMapping(value = "save")
	public String save(Imageinfo imageinfo, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, imageinfo)){
			return form(imageinfo, model);
		}
		imageinfoService.save(imageinfo);
		//addMessage(redirectAttributes, "保存图片信息成功");
		//return "redirect:"+Global.getAdminPath()+"/cms/imageinfo/?repage";
		model.addAttribute("imageinfo", imageinfo);
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		model.addAttribute("opt","save");
		model.addAttribute("message","保存图片信息成功");
		return "modules/cms/imageinfoForm";
	}
	
	@RequiresPermissions("cms:imageinfo:edit")
	@RequestMapping(value = "delete")
	public String delete(Imageinfo imageinfo, RedirectAttributes redirectAttributes) {
		imageinfoService.delete(imageinfo);
		addMessage(redirectAttributes, "删除图片信息成功");
		return "redirect:"+Global.getAdminPath()+"/cms/imageinfo/?repage";
	}

	@RequiresPermissions("cms:imageinfo:edit")
	@RequestMapping(value = "batchDelete")
	public String delete(String ids, RedirectAttributes redirectAttributes) {
		imageinfoService.delete(ids);
		addMessage(redirectAttributes, "删除图片信息成功");
		return "redirect:"+Global.getAdminPath()+"/cms/imageinfo/?repage";
	}
	
	/**
	 * 跳转到图片剪裁页面
	 * @param imageinfo
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequiresPermissions("cms:imageinfo:view")
	@RequestMapping(value = {"imageView"})
	public String imageView(Imageinfo imageinfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		String imgUrl = request.getParameter("imgUrl");
		if(!StringUtils.isEmpty(imgUrl)){
			String imageSource = imgUrl;
			imageSource = Encodes.urlDecode(imageSource);
			imageSource = Encodes.unescapeHtml(imageSource);
			
			imageSource = imageSource.substring(imageSource.substring(1).indexOf("/")+1);
			imageSource = Global.getUserfilesBaseDir()+imageSource;
			File imageFile = new File(imageSource);
			if(imageFile.exists()){
				try {
					BufferedImage images = ImageIO.read(imageFile );
					Integer imageWidth = images.getWidth();
					Integer imageHeight = images.getHeight();
					model.addAttribute("imageWidth", imageWidth);
					model.addAttribute("imageHeight", imageHeight);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			model.addAttribute("imgUrl", imgUrl);
		}
		String inputId = request.getParameter("inputId");
		String callbackFun = request.getParameter("callbackFun");
		model.addAttribute("inputId", inputId);
		model.addAttribute("callbackFun", callbackFun);
		return "modules/cms/cropTool";
	}
	
	/**
	 * 图片剪裁
	 * @param cropImage
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "cropImage")
	public Map cropImage(CropImage cropImage,HttpServletRequest request, HttpServletResponse response, Model model){
		
		String imageSource = cropImage.getImageSource();
		imageSource = Encodes.urlDecode(imageSource);
		imageSource = Encodes.unescapeHtml(imageSource);
		System.out.println(imageSource);
		imageSource = imageSource.substring(imageSource.substring(1).indexOf("/")+1);
		String imageTaget = cropImage.getImageTaget();
		String suffix = imageSource.substring(imageSource.lastIndexOf(".")+1);
		String prefix = imageSource.substring(0,imageSource.lastIndexOf("."));
		String cutImg = prefix+'_'+System.currentTimeMillis()+"."+suffix;
		if(imageTaget == null){
			imageTaget = Global.getUserfilesBaseDir()+""+cutImg;
		}
		String outImg =request.getContextPath() +""+cutImg;
		imageSource = Global.getUserfilesBaseDir()+imageSource;
		
		Map<String , Object> map = new HashMap<String, Object>();
		try {
			ImageUtils.cropImage(cropImage, imageSource, imageTaget);
			map.put("imgRet", outImg);
			map.put("message", "图片裁剪完成");
			map.put("status", 1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			map.put("message", "图片裁剪失败");
			map.put("status", 2);
			return map;
		}
		
		return map;
	}
	
	/**
	 * 图片裁剪
	 * @param imgUrl
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "zoomImage")
	public Map zoomImage(String imgUrl,Double width,Double height,HttpServletRequest request, HttpServletResponse response, Model model){
		Map<String , Object> map = new HashMap<String, Object>();
		String imageSource = StringEscapeUtils.unescapeHtml(imgUrl);
		imageSource = imageSource.substring(imageSource.substring(1).indexOf("/")+1);
		String suffix = imageSource.substring(imageSource.lastIndexOf(".")+1);
		String prefix = imageSource.substring(0,imageSource.lastIndexOf("."));
		String cutImg = prefix+'_'+System.currentTimeMillis()+"."+suffix;
		String imageTaget = Global.getUserfilesBaseDir()+""+cutImg;
		String outImg =request.getContextPath() +""+cutImg;
		imageSource = Global.getUserfilesBaseDir()+imageSource;
		
		try {
			ImageUtils.zoomImageBySize(imageSource, imageTaget, width, height);
			map.put("imgUrl", outImg);
			map.put("message", "图片缩放完成");
			map.put("status", 1);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			e.printStackTrace();
			map.put("message", "图片缩放失败");
			map.put("status", 2);
			return map;
		}
		return map;
	}
	
	@SuppressWarnings("rawtypes")
	@ResponseBody
	@RequestMapping(value = "deleteImage")
	public Map deleteImage(String imgUrl,HttpServletRequest request, HttpServletResponse response, Model model){
		Map<String , Object> map = new HashMap<String, Object>();
		String imageSource = imgUrl;
		if(!StringUtils.isEmpty(imageSource)){
			imageSource = Encodes.urlDecode(imageSource);
			imageSource = Encodes.unescapeHtml(imageSource);
			imageSource = imageSource.substring(imageSource.substring(1).indexOf("/")+1);
			imageSource = Global.getUserfilesBaseDir()+imageSource;
			
			File file = new File(imageSource);
			file.delete();
			map.put("imgUrl", imgUrl);
			map.put("message", "图片删除成功");
		}
		map.put("status", 1);
		return map;
	}
	
	@RequiresUser
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String module, @RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		
		return mapList;
	}
	
	
	
}